//
//  SearchResultViewController.m
//  HuateVideo
//
//  Created by Tiger on 12-8-26.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SearchResultViewController.h"
#import "CommonWebServices.h"
#import "DataList.h"
#import "DetailViewController.h"
#import "Movie.h"

@interface SearchResultViewController ()

@end

@implementation SearchResultViewController
@synthesize searchKey;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [requestArray makeObjectsPerformSelector:@selector(cancelRequest)];
    
    if (downloaderArray.count) {
        [downloaderArray makeObjectsPerformSelector:@selector(cancelDownload)];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.title = searchKey;
    
    
    requestArray = [[NSMutableArray alloc]init];
    downloaderArray = [[NSMutableArray alloc]init];
    array = [[NSMutableArray alloc]init];
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 367)];
    table.dataSource = self;
    table.delegate = self;
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    table.backgroundColor = [UIColor clearColor];
    [self.view addSubview:table];
    
    [self.view showProgressText:YES];
    
    CommonWebServices *webServ = [[CommonWebServices alloc] init];
    webServ.delegate = self;
    [requestArray addObject:webServ];
    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    [parma setValue:searchKey forKey:@"what"];
    [webServ startRequestWithMode:@"Default" Action:@"GetCmspubnewsByNewstitle" Parma:parma Class:@"DataList" RootXML:@"GetCmspubnewsByNewstitleResult" resultIsArray:YES];
    [webServ release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)onCommonWebServicesWithCustomClass:(id)object tag:(NSInteger)tag{
    NSArray *list = ((DataList *)object).List;
    
    if ([list count]>0) {
        [array addObjectsFromArray:list];
        
        [table reloadData];
    }
    
    [self.view showProgressText:NO];
}

- (void)onCommonWebServicesFaild
{
    UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"加载失败")  
                                                        message:LS(@"请检查网络连接和设置")
                                                       delegate:self 	
                                              cancelButtonTitle:LS(@"确定")
                                              otherButtonTitles:nil];		
    [alertview show];		
    [alertview release];
    
    [self.view showProgressText:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [array count];
}

- (void)downImg:(NSDictionary*)dic {
	id movie=[dic valueForKey:@"item"];
	int tag=[[dic valueForKey:@"rowNum"] row];
	ImageDownloader* downloader=[[ImageDownloader alloc] init];
	downloader.imageURL=[movie News_pic];
	downloader.delegate=self;
	downloader.tag=tag;
	[downloader startDownload:YES];
	[downloaderArray addObject:downloader];
	[downloader release];
	
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	static NSString* ListIdentifier = @"ListIdentifier";
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ListIdentifier];
	
	if (cell == nil)
	{
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ListIdentifier];
		//cell.selectionStyle = UITableViewCellSelectionStyleNone;  //去掉选中时的颜色
	}
	
	for (UIView* subView in [cell.contentView subviews])
	{
		[subView removeFromSuperview];
	}
    
	if (indexPath.row < [array count]) {
        
        id movie = [array objectAtIndex:indexPath.row];
		
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 75, 95)];
        image.tag=1000;
        [cell.contentView addSubview:image];
        [image release];
        NSString*imgurl=[movie News_pic];
        NSLog(@"%@=========\n%@",[movie News_title],imgurl);
        if ((![imgurl isEqual:[NSNull null]])&&imgurl.length>0) {
            //            Cache* cache=[CacheManager queryCacheWithCacheKey:imgurl];
            UIImage*tImg=[movie iconImg];
			if (tImg) {
                //                NSData *data = [NSData dataWithContentsOfFile: cache.cobject];
                //                image.image = [UIImage imageWithData: data];
				image.image=[movie iconImg];
            }else {
                image.image = [UIImage imageNamed:@"dengdai.png"];
				NSDictionary* dic=[NSDictionary dictionaryWithObjectsAndKeys:movie,@"item",indexPath,@"rowNum",nil];
				[self performSelector:@selector(downImg:) withObject:dic afterDelay:0.2];
            }
        }
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(95, 10, 200, 20)];
        label.text = [movie News_title];
        label.textColor = LIGHT_COLOR;
        label.font = [UIFont systemFontOfSize:16.0];
        label.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:label];
        [label release];
		
        label = [[UILabel alloc]initWithFrame:CGRectMake(95, 35, 200, 20)];
        label.text = [NSString stringWithFormat:@"%@: %@",LS(@"导演"),[movie News_arg3]];
        label.textColor = [UIColor lightGrayColor];
        label.font = [UIFont systemFontOfSize:14.0];
        label.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:label];
        [label release];
        if ([movie detailType]==MovieChannelTypeNews) {
            label.text=[NSString stringWithFormat:@"%@: %@",LS(@"发布时间"),[movie News_pub_time]];
        }
        if ([movie detailType]==MovieChannelTypeMicroViedo) {
            label.text=[NSString stringWithFormat:@"%@: %@",LS(@"上传者"),[movie News_author]];
        }
        if ([movie detailType]==MovieChannelTypeOriginal) {
            label.text=[NSString stringWithFormat:@"%@: %@",LS(@"拍摄时间"),[movie News_arg5]];
        }
        if ([movie detailType]==MovieChannelTypeMusic) {
            label.text=[NSString stringWithFormat:@"%@: %@",LS(@"歌手"),[movie News_author]];
        }
        label = [[UILabel alloc]initWithFrame:CGRectMake(95, 60, 200, 20)];
        label.text = [NSString stringWithFormat:@"%@: %@",LS(@"主演"),[movie News_arg2]];
        label.textColor = [UIColor lightGrayColor];
        label.font = [UIFont systemFontOfSize:14.0];
        label.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:label];
        [label release];
        
        if ([movie detailType]==MovieChannelTypeNews) {
            label.frame=CGRectMake(95, 60, 200, 40);
            label.numberOfLines=0;
            //            label.text=@"乌鲁木齐6月开始进行田字工程施工，届时所有车辆需绕道行驶...";
        }
        if ([movie detailType]==MovieChannelTypeMicroViedo) {
            label.text=[NSString stringWithFormat:@"%@: %@",LS(@"上传时间"),[movie News_arg5]];
        }
        if ([movie detailType]==MovieChannelTypeMusic) {
            label.text=[NSString stringWithFormat:@"%@: %@",LS(@"专辑"),[movie News_arg1]];
        }
        if ([movie detailType]==MovieChannelTypeOriginal||[movie detailType]==MovieChannelTypeNews) {
            NSString*content=[movie News_content];
            if (content) {
                CFShow(content);
            }
            label.text=[NSString stringWithFormat:@"%@: %@",LS(@"摘要简介"),content];
        }
        if ([movie detailType]!=MovieChannelTypeMusic && [movie detailType]!=MovieChannelTypeNews){
            label = [[UILabel alloc]initWithFrame:CGRectMake(95, 85, 200, 20)];
            label.text = [NSString stringWithFormat:@"%@: %d%@",LS(@"总播放"),[movie News_click_count],LS(@"次")];
            label.textColor = [UIColor lightGrayColor];
            label.font = [UIFont systemFontOfSize:14.0];
            label.backgroundColor = [UIColor clearColor];
            [cell.contentView addSubview:label];
            [label release];
        }
        
        UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 114, 320, 2)];
        line.image = [UIImage imageNamed:@"fengexian.png"];
        [cell.contentView addSubview:line];
        [line release];
    }
	
	cell.backgroundColor = [UIColor clearColor];
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < [array count]) {
        id movie = [array objectAtIndex:indexPath.row];
        NSLog(@"%@",movie);
        DetailViewController *detailViewController = [[DetailViewController alloc]init];
        detailViewController.movie = movie;
        detailViewController.type = 2;
        detailViewController.channelType = MovieChannelTypeMovie;//[movie detailType];
        [self.navigationController pushViewController:detailViewController animated:YES];
        [detailViewController release];
    }
}
#pragma mark imagedownloaderDelegate
- (void)appImageDidLoad:(UIImage *)image withTag:(int)tag{
    NSLog(@"load ++++++++%d",tag);
	id t_movie=[array objectAtIndex:tag];
    UITableViewCell* cell=[table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:tag inSection:0]];
    UIImageView* img=(UIImageView*)[cell.contentView viewWithTag:1000];
    if (image) {
		[t_movie setIconImg:image];
        img.image=image;
    }
}

@end
